// --------------------------------------------------------------------
// TCP服务端头文件声明
// --------------------------------------------------------------------

#include "../sock.hpp"
#include <functional>
#include <unordered_map>
#include "threadpool.hpp"
#include <memory>
#include <mutex>
#include <queue>
#if __cplusplus >= 201103L
#include <future>
#include <type_traits>
#endif

namespace ymbxSock
{

    typedef std::function<void(const std::string &req, std::string *resp)> Handler;
    using TaskHandler=std::function<std::string(const std::string&)>;

    struct connSock
    {
        int sock;
        std::string ip;
        uint16_t port;
        bool status;
    };
#if __cplusplus < 201103L
    class threadWork
    {
    public:
        threadWork(int csock, const Handler &handler, std::shared_ptr<std::unordered_map<int, connSock>> conns);
        void operator()();

    private:
        int _csock;
        Handler _handler;
        std::shared_ptr<std::unordered_map<int, connSock>> _conns;
    };
#endif
    class tcpSrv
    {
    public:
        tcpSrv(uint16_t port);
#if __cplusplus >= 201103L
        void Start();
        void handlerClient(int sock, const std::string &ip, uint16_t port);
        std::string processTask(const std::string &mes);
        std::string parseReq(const std::string& req,std::string* taskData);
        
        void addTask(const std::string& taskname,TaskHandler taskhandler);
        void removeTask(const std::string& taskname);
        
        
#else 
        void Start(const Handler& handler);
#endif
        ~tcpSrv();

    private:
        ymbxTcpSocket _sock;
        uint16_t _port;
        std::shared_ptr<std::unordered_map<int, connSock>> _conns;
        
        // #if __cpluscplus<201103L
        //         pthread_mutex_t _mtx;
        //         ymbxUtil::threadPool<threadWork> _tpools;
        // #else
        std::mutex _conn_mtx;
        ymbxUtil::threadPool _tpools;
        
        std::unordered_map<std::string,TaskHandler> _tasks;
        TaskHandler _defaulthandler;
        std::mutex _task_mtx;

        // #endif
    };
}